package com.nhatth.contactsharer;

import java.util.Vector;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements ContactListFragment.OnContactSelectedListener, SelectedContactFragment.OnContactUncheckListener {
	
	View countLayout;
	static final String TAG = "ContactSharerActivity";
	Vector<Contact> checkedValue;
	MyAdapter fragmentAdapter;
	ViewPager vp;
	PagerTitleStrip strip;
	SelectedContactAdapter mSelectedAdapter;
	public ProgressDialog pd;
	
	//Khởi tạo mọi thứ
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        //show progress dialog
        pd = ProgressDialog.show(this, "Please wait...", "Loading data from Contacts");
        Log.d(TAG, "shown progess dialog");
        Thread t = Thread.currentThread();
		Log.d(TAG, "in thread: "+t.getName());
        //đặt cái view cho activity này
        setContentView(R.layout.activity_main);
        //tạo vector để đựng selected contact
        checkedValue = new Vector<Contact>();
        //tạo adapter cho SelectedContactFragment
        mSelectedAdapter = new SelectedContactAdapter(this, R.id.list_selected_name);
        //bind luôn dữ liệu cho mCheckedAdapter
        mSelectedAdapter.addAll(checkedValue);
        //Set listener khi mà một item của mCheckedAdapter bị remove
        mSelectedAdapter.removedListener = (OnContactRemovedListener) new OnContactRemoved();
        //tạo một cái fragment adapter mới
        fragmentAdapter = new MyAdapter(getSupportFragmentManager());
        vp = (ViewPager) findViewById(R.id.slide_layout_pager);
        vp.setAdapter(fragmentAdapter);
        strip = (PagerTitleStrip) findViewById(R.id.pager_title_strip);
        TextView lblCount = (TextView) findViewById(R.id.textView1);
		lblCount.setText("Bạn đang chọn " + checkedValue.size() + " số.");
    }

    @Override
    protected void onResume() {
    	super.onResume();
    	Log.d(TAG, "onResume");
    }
    
    @Override
    protected void onStop() {
    	super.onStop();
    	Log.d(TAG, "onStop");
    }
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	Log.d(TAG, "onDestroy");
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

	public void onContactSelected(Contact con) {
		if (!checkedValue.contains(con)) {
			con.checked = true;
			checkedValue.add(con);
			mSelectedAdapter.add(con);
		}
		else {
			con.checked = false;
			checkedValue.remove(con);
			mSelectedAdapter.remove(con);
		}
		refreshCount();
		mSelectedAdapter.notifyDataSetChanged();
		SelectedContactFragment slc = (SelectedContactFragment) fragmentAdapter.selectedFrag;
		if(slc.isInLayout()){
			slc.refreshList();
		}
	}
	
	//Khi chọn option trong menu
		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			int id = item.getItemId();
			switch (id) {
			//Gửi đi
			case R.id.activityMain_share:
				Log.i(TAG, "Clicked on Menu!");
				if (checkedValue.isEmpty()) {
					Context ctx = getApplicationContext();
					CharSequence message = "Bạn chưa chọn số nào!";
					Toast.makeText(ctx, message, Toast.LENGTH_SHORT).show();
				} else {
					long[] idArray = new long[checkedValue.size()];
					int index = 0;
					for (Contact con : checkedValue) {
						idArray[index] = con._id;
						index++;
					}
					Intent i = new Intent(this, ComfirmActivity.class);
					i.putExtra("contacts_id", idArray);
					startActivity(i);
				}
				break;
			//Xóa hết
			case R.id.activityMain_clear:
				for (Contact con : checkedValue) {
					con.checked = false;
				}
				checkedValue.clear();
				refreshCount();
				ContactListFragment clf = (ContactListFragment) fragmentAdapter.allFrag;
				clf.uncheckAll();
				mSelectedAdapter.clear();
				mSelectedAdapter.notifyDataSetChanged();
				break;
			}
		return true;
	}
	
	//Xử lý liên lạc giữa MainActivity và ContactListFragment
	public Vector<Contact> getSelectedContact() {
		return checkedValue;
	}
	
	//Xử lý liên lạc giữa MainActivity và SelectedContactListFragment
	public void OnContactUncheck(Contact con) {
//		con.checked = false;
//		checkedValue.remove(con);
//		ContactListFragment clf = (ContactListFragment) fragmentAdapter.allFrag;
//		clf.uncheck(con);
//		mSelectedAdapter.remove(con);
//		mSelectedAdapter.notifyDataSetChanged();
//		fragmentAdapter.selectedFrag.refreshList();
	}
	
	//Dùng listener để xử lý liên lạc giữa MainActivity và SelectedContactAdapter
	private class OnContactRemoved implements OnContactRemovedListener
	{
		public void onRemove(Contact con) {
			con.checked = false;
			checkedValue.remove(con);
			ContactListFragment clf = (ContactListFragment) fragmentAdapter.allFrag;
			clf.uncheck(con);
			refreshCount();
		}
	}

	public SelectedContactAdapter getCheckedAdapter() {
		return mSelectedAdapter;
	}

	private void refreshCount() {
		int count = checkedValue.size();
		TextView lblCount = (TextView) findViewById(R.id.textView1);
		lblCount.setText("Bạn đang chọn " + count + " số.");
	}
}

class MyAdapter extends FragmentPagerAdapter {

	public ContactListFragment allFrag = null;
	public SelectedContactFragment selectedFrag = null;
	
	public MyAdapter(FragmentManager fm) {
		super(fm);
		allFrag = new ContactListFragment();
		selectedFrag = new SelectedContactFragment();
	}

	@Override
	public Fragment getItem(int index) {
		Fragment frag=null;
		switch(index)
		{
			case 0:
				frag = allFrag;
				break;
			case 1:
				frag = selectedFrag;
				break;
		}
		return frag;
	}

	
	@Override
	public CharSequence getPageTitle(int position) {
		CharSequence title="";
		switch(position) {
		case 0:
			title = "All Contacts";
			break;
		case 1:
			title = "Selected Contacts";
			break;
		}
		return title;
	}
	@Override
	public int getCount() {
		return 2;
	}
}